/**
 * @ author: 汪孟苹
 */
define(["jquery","bootstrap","bbcare","comm/form/form","bch/app/workBench/workBench.servers","bch/app/workBench/workBench.ui"],function($,bootstrap,$bb,$form,$servers,$ui){
	var event = {};
	var defaults;

	/**
	 * 建档成功后的回调函数
	 */
	var ajaxArchiveCallBack = function(data,className){
		$("."+className).modal("hide");
		$bb.toastShow("添加成功！");
		var arg = {
			"userId":data.id,
			"busiTypeList":defaults.busiTypeList,
		}
		setTimeout(function(){
			$bb.openPage("bch_user",arg);
		},3000);
	}

	/**
	 * 建档保存
	 */
	var onArchiveSave = function(){
		if( $form.validate("archiveBox") ){
			var params = $(this).data("params");
			var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
			var contList = $form.getSaveData("archiveBox");
			var userName = $bb.code.getValueByName("archiveBox","userName");
			var channelId = $bb.getChannelId();
			var taskIdList = $servers.getTaskIdList(params.questions);
			if( $(".schemes-box").length == 0 ){
				var schemeId = params.schemeId;
			}else if( $(".schemes-box input[name=scheme]").length > 0 ){
				var schemeId = $(".schemes-box input[name=scheme]:checked").val();
			}else if( $(".schemes-box select[name=scheme]").length > 0 ){
				var schemeId = $(".schemes-box select[name=scheme]").val();
			}
			var params1 = {
				"oprInfo":{
					"opCode":"1000",
					"opType":"2",
					"opNote":"【"+doctorName+"】医生添加【"+userName+"】患者",
					"channelType":"2", // web端门诊渠道:2
					"channelId":channelId,
				},
				"archiveInfo":{
					"queueId":params.queueId,
					"contList":contList,
					"schemeId":schemeId,
					"taskIdList":taskIdList,
				},
			};
			$servers.ajaxArchive(params1,ajaxArchiveCallBack,params.className);
		}
	}

	/**
	 * 选择不同的临床路径
	 */
	var onSchemeSelect = function(){
		var params = $(this).data("params");
		delete params.questions;
		if( $(this)[0].tagName.toLowerCase() == "input" ){
			var schemeId =  $(this).parents(".radio").find("input:checked").val();
		}else if( $(this)[0].tagName.toLowerCase() == "select" ){
			var schemeId =  $(this).val();
		}
		$.extend(params,{"schemeId":schemeId});
		$servers.ajaxArchiveTaskAndCont(params,ajaxArchiveTaskAndContCallBack);
	}

	/**
	 * 建档任务查询，同时返回任务内容（问卷）模板,成功后的回调函数
	 */
	var ajaxArchiveTaskAndContCallBack = function(data,params){
		if( !params.questions ){
			if( data.taskList && data.taskList.length > 0 ){
				params.questions = data.taskList;
			}else if( data.contList && data.contList.length > 0 ){
				params.questions = data.contList;
			}
		}
		$.extend(params,{"queueId":data.queueId,"schemeId":data.schemeId});
		if( params.questions && params.questions.length > 0 ){
			$form.init({
				"id":"archiveBox",
				"questions":params.questions,
				"values":data.valueList,
				"event":{
					"autoCompleteCallBack":ajaxArchiveTaskAndContCallBack,
					"autoCompleteParams":params
				}
			});
			$("."+params.className).modal("show");
			// 选择不同的临床路径
			$(".schemes-box input[name=scheme],.schemes-box select[name=scheme]").unbind("change");
			$(".schemes-box input[name=scheme],.schemes-box select[name=scheme]").data("params",params);
			$(".schemes-box input[name=scheme],.schemes-box select[name=scheme]").change(onSchemeSelect);
			// 建档保存
			$("#archiveSave").unbind("click");
			$("#archiveSave").data("params",params);
			$("#archiveSave").click(onArchiveSave);
		}
	}

	/**
	 * 建档
	 */
	var archiveWrap = function(schemes,queueId,className){
		$ui.archiveWrap({
			"dom":$("."+className + " .modal-body"),
			"list":schemes
		});
		var defaultScheme = $servers.getDefaultScheme(schemes);
		var params = {
			"queueId":queueId,
			"schemeId":defaultScheme.id,
			"className":className,
		}
		$servers.ajaxArchiveTaskAndCont(params,ajaxArchiveTaskAndContCallBack);
	}

	/**
	 * 请求临床路径成功后的回调函数
	 */
	var ajaxQueueCpCallBack = function(data,queueId){
		var className = "archiveModal";
		$bb.modal({
			"className":className,
			"tit":"添加患者",
			"size":"modal-lg"
		},function(){
			archiveWrap(data.rows,queueId,className);
		});
	}

	/**
	 * 点击队列，在该队列中新增患者
	 */
	var onQueueSelect = function(){
		var className = $(this).data("className");
		var queueId = $(this).attr("data-queueId");
		$("."+className).modal("hide");
		$servers.ajaxQueueCp(queueId,ajaxQueueCpCallBack);
	}

	/**
	 * 模态框队列卡片初始化
	 */
	var queueCardInit = function(queueList,className){
		$ui.queueCard({
			"dom":$("." + className + " .modal-body"),
			"list":queueList
		});
		$("."+className).modal("show");
		$("." + className + " .modal-body .modal-addPatient div").unbind("click");
		$("." + className + " .modal-body .modal-addPatient div").data("className",className);
		$("." + className + " .modal-body .modal-addPatient div").click(onQueueSelect);
	}

	/**
	 * 请求队列成功后的回调函数
	 */
	var ajaxQueueCallBackAdd = function(data){
		var className = "queueModal"; // 模态框的类名
		$bb.modal({
			"className":className,
			"tit":"请选择建档队列"
		},function(){
			queueCardInit(data.queueList,className);
		});
	}

	/**
	 * 点击"添加患者"按钮弹出模态框
	 */
	var onAddPatientClick = function(){
		$servers.ajaxQueue(ajaxQueueCallBackAdd,{"subBusiType":"B0105"});
	}; 

	/**
	 * 点击随访患者卡片进入详情页
	 */
	var onBabyCardClick = function(){
		var remark = $(this).attr("remark");
		var userId = $(this).attr("userId");
		var params = { "userId":userId };
		if( remark == "B0105" ){
			$bb.openPage("bch_lapseToDetail",params);
		}else{
			$.extend(params,{"busiTypeList": defaults.busiTypeList});
			$bb.openPage("bch_user",params);
		}
	};
	/**
	 * 点击今日门诊患者跳转
	 */
	var onBabyClick = function(){
		var data = $(this).data("data");
		var index = $(this).index();
		var curData = data.values[index];
		var params = { "userId":curData.userId };
		if( curData.remark == "B0105" ){
			$bb.openPage("bch_lapseToDetail",params);
		}else{
			$.extend(params,{"busiTypeList": defaults.busiTypeList});
			$bb.openPage("bch_user",params);
		}
	}

	/**
	 * 窗口期计划随访患者/计划随访患者（tit根据flag不同有所不同）
	 */
	var windowTitText = function(params){
		var text;
		switch(params.qryStatus){
			case "":
				text = "随访患者";
				break;
			case "00":
				text = "窗口期计划随访患者";
				break;
			case "01":
				text = "入组待审核随访患者";
				break;
			case "02":
				text = "主诉待确认随访患者";
				break;
			case "03":
				text = "临期未随访随访患者";
				break;
			case "04":
				text = "已失访随访患者";
				break;
		}
		$("#windowTit").html(text);	
	};
	/**
	 * 查询
	 */
	var onSearch = function(){
		var userName;
		if( $(this)[0].tagName.toLowerCase() == "span" ){
			$(this).prev().val("");
		}else if( $(this)[0].tagName.toLowerCase() == "button" ){
			userName = $(this).html();
		}
		var arg = $(this).data();
		var fuzzyVar = $("#windowKeyword input").val();
		var queueId = $("#selectQueue").val();
		var qryStatus = $("#qryStatus").val();
		var params = {
			"page":1,
			"rows":arg.rows,
			"fuzzyVar":fuzzyVar,
			"queueId":queueId,
			"qryStatus":qryStatus,
			"userName":userName,
			"busiTypeList":arg.busiTypeList,
		};
		var reg = /^1\d{10}$/;
		reg.test(params.fuzzyVar) ? $.extend(params,{phoneNum:params.fuzzyVar}) : delete params.phoneNum;
		windowTitText(params);
		userListInit(params);
	}
	/**
	 * 请求窗口期计划随访患者成功后的回调函数
	 */
	var ajaxUserListCallBack = function(data,params){
		if(data && data.rows && data.rows.length > 0){
			var pagesAll = Math.ceil(data.total / params.rows);
			$ui.babyList({
				id:"windowBabyList",
				list:data.rows,
				rows:params.rows
			});
			// 初始化所有工具提示
		    $(function(){$("[data-toggle='tooltip']").tooltip();});
			// 翻页
			$bb.page.init({
				"id":"windowBottomPage",
				"pagesAll":pagesAll,
				"page":params.page,
				"params":params,
				"callback":userListInit,
			});
			/* 点击随访患者卡片进入详情页 */
			$("#windowBabyList .clickbabycard").unbind("click");
			//$("#windowBabyList .clickbabycard").data("busiTypeList",params.busiTypeList);
			$("#windowBabyList .clickbabycard").click(onBabyCardClick);
		}else{
			$("#windowBabyList").html('<div class="col-sm-12 col-md-12 babycard-null">暂无数据..</div>');
			$("#windowBottomPage").html("");
		}
		/* 姓名、手机号码查询 */
		$("#windowKeyword span").unbind("click");
		$("#windowKeyword span").data(params);
		$("#windowKeyword span").click(onSearch);
		$("#windowKeyword input").unbind("input propertychange");
		$("#windowKeyword input").data(params);
		$("#windowKeyword input").bind("input propertychange",onSearch);
		/* 队列查询 状态查询 */
		$("#selectQueue,#qryStatus").unbind("change");
		$("#selectQueue,#qryStatus").data(params);
		$("#selectQueue,#qryStatus").bind("change",onSearch);
	};

	/**
	 * 患者列表
	 */
	var userListInit = function(params){
		$servers.ajaxUserList(params,ajaxUserListCallBack);
	}

	/**
	 * 请求队列成功后的回调函数
	 */
	var ajaxQueueCallBack = function(data){
		$ui.queue({
			"id": "selectQueue",
			"list": data.queueList
		});
		$(".dashboard-add #addPatient").unbind("click");
		$(".dashboard-add #addPatient").click(onAddPatientClick);
	}
	/**
	 * 请求统计数据成功后的回调函数
	 */
	var ajaxStatisCallBack = function(data){
		$ui.windowPt({
			id:"windowBottomStatistics",
			list: data
		});
		$ui.windowTop({
			id:"dashboardCardlist",
			list: data
		});
		$servers.ajaxQueue(ajaxQueueCallBack);
	}
	/**
	 * 请求常用姓氏成功后的回调函数
	 */
	var ajaxSurnameListCallBack = function(data,params){
		if(data.surNameList){
			$ui.firstNameInit({
				id:"windowFirstName",
				list:data.surNameList,
			});
			// 姓氏查询
			$("#windowFirstName button").unbind("click");
			$("#windowFirstName button").data(params);
			$("#windowFirstName button").click(onSearch);
		}
	}
	/**
	 * 请求今日门诊记录成功后的回调函数
	 */
	var ajaxUserOprListCallBack = function(data,params){
		$ui.userOprList({
			id:"patientOperateListQuery",
			list:data.rows
		});
		$("#patientOperateListQuery .baby-done").unbind("click");
		$("#patientOperateListQuery .baby-done").data({"data":{"values":data.rows}});
		$("#patientOperateListQuery .baby-done").click(onBabyClick);
	}

	var init = function(){
		defaults = $bb.getPageParams();
		$servers.ajaxStatis(defaults,ajaxStatisCallBack);
		// 获取参数
		var rows = document.body.offsetWidth < 992 ? 2 : document.body.offsetWidth <1200 ? 3 : 4;
		var qryStatus = $("#qryStatus").val();
		var params = {
			"page":1,
			"rows":4*rows,
			"qryStatus":qryStatus,
			"busiTypeList":defaults.busiTypeList,
		};
		// 患者列表
		userListInit(params);
		// 姓氏
		$servers.ajaxSurnameList(params,ajaxSurnameListCallBack);
		// 操作记录
		var params1 = $.extend({},params,{"rows":11,"flag":"01","isFree":"1"});
		$servers.ajaxUserOprList(params1,ajaxUserOprListCallBack);
	}
	event.init = init;
	
	return event;
});
